<?php
require_once 'CMS/Util.php';
require_once 'CMS/Mvc/BaseController.php';
require_once 'CMS/Mvc/BaseUserController.php';
require_once 'CMS/UserCommon.php';
require_once 'CMS/User.php';
require_once 'CMS/Language.php'; //include thu vien language
require_once 'CMS/Pagination.php';

//Người tạo : Huỳnh Trọng Hiếu - Team 4
//Module 	: Search
//Chức năng	: Tìm kiếm
 
class SearchController extends BaseUserController{
	private $pagination;
	public function init(){
		parent::init();
		$tbSetting = new User_Model_Parameter();
		$temp = $tbSetting->selectSetting("config");
		$layout = unserialize($temp[0]["parameter_value"]);
		if($layout['config_template'] !="")
		{
			$this->_helper->layout()->setLayout($layout['config_template']);
			$_SESSION['config_template'] = $layout['config_template'];
		}
		else
		{
			$this->_helper->layout()->setLayout('layoutmain');
			$_SESSION['config_template'] = 'layoutmain';
		}
	}

//Action index thực hiện chức năng xử lý dữ liệu đăng ký
    public function indexAction(){
    	$_SESSION['page_code'] = 'search';
		
		$tbSidebarModule = new User_Model_SidebarModule();
		$Modules = $tbSidebarModule->selectAllModule();
		foreach($Modules as $module)
		{
			$database_show_widget [] = $module["module_code"];
			$database_order_widget [$module["module_code"]] =  $module["sort_order"];
		}
		
		$tbDefaultbarModule = new User_Model_DefaultModuleToPage();
		$defaultModules = $tbDefaultbarModule->selectAllModule("search");
		foreach($defaultModules as $dmodule)
		{
			$content_show_widget [] = $dmodule["module_code"];
			$content_order_widget [$dmodule["module_code"]] =  $dmodule["sort_order"];
		}
		
		$tbContentbarModule = new User_Model_ContentModuleToPage();
		// mac dinh homepage
		$ContentModules = $tbContentbarModule->selectAllModule("search");	
		foreach($ContentModules as $cmodule)
		{
			$content_show_widget [] = $cmodule["module_code"];
			$content_order_widget [$cmodule["module_code"]] =  $cmodule["sort_order"];
		}	
		
		$front     = Zend_Controller_Front::getInstance();
		$widgets = $front->getPlugins();
	
		foreach($widgets as $widget)
		{
			if(count($Modules) > 0){
				if($widget->name !="" && in_array($widget->name, $database_show_widget))
				{
					$widget->enable = 1;
					$widget->order = $database_order_widget[$widget->name];
				}
			}
			if(count($content_show_widget) > 0){
				if($widget->name !="" && in_array($widget->name, $content_show_widget))
				{
						$widget->enable = 1;
						$widget->order = $content_order_widget[$widget->name];
				}		
			}
		}
		
		
    	/*========== Start Load Language ==========*/
			$language = new Language(APPLICATION_PATH . '/modules/user/languages/search');
			if(isset($_SESSION['language']))
			{
				$language_id = $_SESSION['language'];
				$tbLanguage = new Language_Model_Language();
				$name = $tbLanguage->getNameLanguage($language_id);
				$language->load($name['name']);
			}
			else
				$language->load('Default');		
			$languages = $tbLanguage->getAllLanguages();
			$this->view->languages = $languages;
		/*========== End Load Language ==========*/
		
		/*========== Start Get Text ==============*/
			$this->view->text_title 	= $language->get('text_title');
			$this->view->text_show 		= $language->get('text_show');
			$this->view->text_detail 	= $language->get('text_detail');
			$this->view->text_nothing 	= $language->get('text_nothing');
			$this->view->text_sort 		= $language->get('text_sort');
			$this->view->text_name_asc 	= $language->get('text_name_asc');
			$this->view->text_name_desc = $language->get('text_name_desc');
			$this->view->text_price_asc = $language->get('text_price_asc');
			$this->view->text_price_desc= $language->get('text_price_desc');
			$this->view->text_date_asc 	= $language->get('text_date_asc');
			$this->view->text_date_desc = $language->get('text_date_desc');
			$this->view->text_update = $language->get('text_update');
			$this->view->btndetail		= $language->get('text_prodetail');
			$this->view->btnadd			= $language->get('text_add');
			$this->view->cdate			= $language->get('text_cdate');
			$this->view->price			= $language->get('text_price');
			$this->view->view			= $language->get('text_view');
		/*========== End Text ==============*/
			
			if(!isset($_GET['search_value'])||!isset($_GET['search_type'])||trim($_GET['search_value'])=="")
				$this->_redirect('/');
			
			$value = $_GET['search_value'];
			$type = $_GET['search_type'];
			
			$this->view->type = $type;
		    switch ($type)
				{
					case 1: $this->view->route = 'index';break;
					case 2: $this->view->route = 'news';break;
					case 3: $this->view->route = 'qa';break;
					default : $this->view->route = 'index';
				}
			if(isset($_GET['show'])) $show = $_GET['show'];
			else $show = 1;
			if(isset($_GET['page'])) $page = $_GET['page'];
			else $page = 1;
			if($type==1)
				$limit = 7;
			else if($type==2)
				$limit = 30;
			else $limit = 12;
			$this->pagination = new Pagination();
			$data_search = array();
			/*========== Test Du Lieu Search ==============*/
			//$tbThings = new User_Model_Things();
			//$data = $tbThings->getAllThingsbyType($type)->toArray();
			//Util::create_index($data,$type);
			/*========== End Test Du Lieu Search ==============*/
			Zend_Search_Lucene_Analysis_Analyzer::setDefault(
               new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8Num_CaseInsensitive());
			Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('utf-8');
    		if($type == 1)
			{
				if($name['name']=='Vietnamese')
					$index = Zend_Search_Lucene::open('index_product_vi');
				else $index = Zend_Search_Lucene::open('index_product_en');
			}
   		 	if($type == 2)
			{
				if($name['name']=='Vietnamese')
					$index = Zend_Search_Lucene::open('index_news_vi');
				else $index = Zend_Search_Lucene::open('index_news_en');
			}
			if($type == 3)
			{
				if($name['name']=='Vietnamese')
					$index = Zend_Search_Lucene::open('index_qa_vi');
				else $index = Zend_Search_Lucene::open('index_qa_en');
			}
			
			 $this->view->content_search = $value;
			 $vowel = array("*","?","+","-","=");
			 $str = str_replace($vowel," ",$value);
			 $del_space = Util::del_space($str);
			 if($del_space!="")
		  	 {
		  		$content_search = str_replace(" ","* ",$del_space);
				$content_search =$content_search."*";
				Zend_Search_Lucene_Search_Query_Wildcard::setMinPrefixLength(1);
				$query = new Zend_Search_Lucene_Search_Query_Boolean();
		        $query_search = Zend_Search_Lucene_Search_QueryParser::parse($content_search);
		        $query->addSubquery($query_search, true);
		        
		  	 	if(isset($_GET['sort']) && $_GET['sort'] != null)
			    {
			    	if($_GET['sort'] == "ten_asc")
			    	{
		        		$hits = $index->find($query,'title',SORT_STRING,SORT_ASC);
			    		$this->view->choose = 1;
			    	}
		        	if($_GET['sort'] == "ten_desc")
		        	{
		        		$hits = $index->find($query,'title',SORT_STRING,SORT_DESC);
		        		$this->view->choose = 2;
		        	}
		        	if($_GET['sort'] == "gia_asc")
		        	{
		        		$hits = $index->find($query,'price',SORT_NUMERIC,SORT_ASC);
		        		$this->view->choose = 3;
		        	}
		        	if($_GET['sort'] == "gia_desc")
		        	{
		        		$hits = $index->find($query,'price',SORT_NUMERIC,SORT_DESC);
		        		$this->view->choose = 4;
		        	}
			    	if($_GET['sort'] == "ngay_asc")
		        	{
		        		$hits = $index->find($query,'update_date',SORT_NUMERIC,SORT_ASC);
		        		$this->view->choose = 5;
		        	}
		        	if($_GET['sort'] == "ngay_desc")
		        	{
		        		$hits = $index->find($query,'update_date',SORT_NUMERIC,SORT_DESC);
		        		$this->view->choose = 6;
		        	}
		        	$sort = '&sort='.$_GET['sort'];
			    }
			    else 
			    {
			    	$sort = "&sort=ten_asc";
			    	$hits = $index->find($query,'title',SORT_STRING,SORT_ASC);
			    	$this->view->choose = 1;
			    }
			    
			    if(isset($hits) && $hits!="" && $hits!=null)
		  		{
		  			$i = 0;
		  			foreach($hits as $row)
					{
						if($i>=($page-1)*$limit && $i<$page*$limit)
						{
							$data_search[$i]['title'] =  Util::highlight($row->title,$del_space);
							$data_search[$i]['avatar'] =  $row->avatar;
							$data_search[$i]['price'] =  $row->price;
							$data_search[$i]['thing_id'] =  $row->thing_id;
							$data_search[$i]['short_description'] =  Util::highlight($row->short_description,$del_space);
							$data_search[$i]['update_date'] =  Util::makeDays($row->update_date);
						}
						$i++;
					}
					
				$this->pagination->init("?show=".$show.$sort."&search_type=".$type."&search_value=".$value."&page=",count($hits),$limit,$page);	
		        $this->view->pagination = $this->pagination->render();
		        	
		  		}
		  	 }
			 if(count($data_search)==0 && $page!=1)
			 	$this->_redirect('/search?search_value='.$value.'&search_type='.$type.'&show='.$show.$sort);
		     $this->view->action_show = '/search?search_value='.$value.'&search_type='.$type.$sort;
		  	 $this->view->action_sort = '/search?search_value='.$value.'&search_type='.$type.'&show='.$show;
		  	 $this->view->data_search = $data_search;
	}
	
	 public function createAction(){
	 	$tbThings = new User_Model_Things();
		$data = $tbThings->getAllThingsbyType(1);
		Util::create_index($data,1);
		$data = $tbThings->getAllThingsbyType(2);
		Util::create_index($data,2);
		$data = $tbThings->getAllThingsbyType(3);
		Util::create_index($data,3);
		
		$this->_helper->json('');
	 }
}